//
//  UITextField+Extension.m
//  TableDemo
//
//  Created by jutuo on 2020/4/1.
//  Copyright © 2020 jutuo. All rights reserved.
//

#import "UITextField+Extension.h"
#import "NSObject+Extension.h"
#import "NSString+Extension.h"
@interface UITextField ()
@property (nonatomic, copy) NSString *historyText;
@end
@implementation UITextField (Extension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        BOOL ex1 = [self swizzleInstanceMethod:@selector(initWithFrame:) with:@selector(initializingWithFrame:)];
        BOOL ex2 = [self swizzleInstanceMethod:@selector(setText:) with:@selector(setTxt:)];
        NSLog(@"交换结果：%d,%d",ex1,ex2);
    });
   
}
- (instancetype)initializingWithFrame:(CGRect)frame
{
    self.formatterType = UITextFieldFormatterTypeAny;
    self.limitLength = INT16_MAX;
    self.characterSet = @"";
    self.decimalPlace = 2;
    return [self initializingWithFrame:frame];
}

- (void)setTxt:(NSString *)text {
    [self setTxt:text];
    self.historyText = text;
}
- (void)setFormatterType:(UITextFieldFormatterType)formatterType
{
    
    switch (formatterType) {
        case UITextFieldFormatterTypePhoneNumber:
            self.limitLength = 11;
        case UITextFieldFormatterTypeNumber:
            self.keyboardType = UIKeyboardTypeNumberPad;
            break;
        case UITextFieldFormatterTypeDecimal:
            self.keyboardType = UIKeyboardTypeDecimalPad;
            break;
        default:
            break;
    }
    objc_setAssociatedObject(self, @selector(formatterType), @(formatterType), OBJC_ASSOCIATION_ASSIGN);
}

- (UITextFieldFormatterType)formatterType
{
    NSNumber *obj = objc_getAssociatedObject(self, _cmd);
    return obj.integerValue;
}

// 2. limitLength 的实现
- (void)setLimitLength:(NSUInteger)limitLength
{
    objc_setAssociatedObject(self, @selector(limitLength), @(limitLength), OBJC_ASSOCIATION_ASSIGN);

}

- (NSUInteger)limitLength
{
    NSNumber *obj = objc_getAssociatedObject(self, _cmd);
    return obj.integerValue;
}

// 3. characterSet 的实现
- (void)setCharacterSet:(NSString *)characterSet
{
    objc_setAssociatedObject(self, @selector(characterSet), characterSet, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)characterSet
{
    id obj = objc_getAssociatedObject(self, _cmd);
    return obj;
}

// 4. decimalPlace 的实现
- (void)setDecimalPlace:(NSUInteger)decimalPlace
{
    if (decimalPlace == 0) {
        decimalPlace = 1;
    }
    objc_setAssociatedObject(self, @selector(decimalPlace), @(decimalPlace), OBJC_ASSOCIATION_ASSIGN);
}

- (NSUInteger)decimalPlace
{
    NSNumber *obj = objc_getAssociatedObject(self, _cmd);
    return obj.integerValue;
}

- (void)setHistoryText:(NSString *)historyText
{
    objc_setAssociatedObject(self, @selector(historyText), historyText, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)historyText
{
    return objc_getAssociatedObject(self, _cmd);
}
- (void)textFieldDidBeginEditing
{
    if (self.historyText.length == 0) return;
    NSString *currentText = self.historyText;
    switch (self.formatterType) {
        case UITextFieldFormatterTypePhoneNumber:
        case UITextFieldFormatterTypeNumber:
            currentText = [currentText disableRegEx:@"[^\\d\r\n]"];
            break;
        case UITextFieldFormatterTypeDecimal:
            currentText = [currentText disableRegEx:@"[^\\d.\r\n]"];
            break;
        case UITextFieldFormatterTypeAlphabet:
            currentText = [currentText disableRegEx:@"[^a-zA-Z]"];
            break;
        case UITextFieldFormatterTypeNumberAndAlphabet:
            currentText = [currentText disableRegEx:@"[^a-zA-Z0-9]"];
            break;
        case UITextFieldFormatterTypeDisableEmoji:
            currentText = [currentText disableEmoji];
            break;
        case UITextFieldFormatterTypeCustom:
            if (!self.characterSet) {
                self.characterSet = @"";
            }
            currentText = [currentText disableRegEx:[NSString stringWithFormat:@"[^%@]",self.characterSet]];
            break;
        default:
            break;
    }
    
    if (currentText.length > self.limitLength) {
        currentText = [currentText substringToIndex:self.limitLength];
    }
    
    self.historyText = currentText;
    self.text = currentText;
}
- (void)textFieldDidChange
{
    NSString *currentText = self.text;
    NSRange locationRange = self.selectedRange;
    BOOL isMatch = YES;
    BOOL isHighLight = NO;
    
    UITextRange *selectRange = [self markedTextRange];
    UITextPosition *position = [self positionFromPosition:selectRange.start offset:0];
    isHighLight = position ? YES: NO;
    
    NSString *regexString = @"[\\s\\S]*";
    switch (self.formatterType) {
        case UITextFieldFormatterTypePhoneNumber:
        case UITextFieldFormatterTypeNumber:
            regexString = @"^[0-9]*$";
            break;
        case UITextFieldFormatterTypeDecimal:
           if (self.decimalPlace == 0) {
               self.decimalPlace = 2;
           }
           regexString = [NSString stringWithFormat:@"^(\\d+)\\.?(\\d{0,%lu})$", (long)self.decimalPlace];
            break;
        case UITextFieldFormatterTypeAlphabet:
            regexString = @"^[a-zA-Z]*$";
            break;
        case UITextFieldFormatterTypeNumberAndAlphabet:
            regexString = @"^[a-zA-Z0-9]*$";
            break;
        case UITextFieldFormatterTypeDisableEmoji:
            currentText = [currentText disableEmoji];
            break;
        case UITextFieldFormatterTypeCustom:
            if (!self.characterSet) {
                self.characterSet = @"";
            }
            regexString = [NSString stringWithFormat:@"^[%@]", self.characterSet];
            break;
        default:
            break;
    }
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexString];
    isMatch = [regexTest evaluateWithObject:currentText];
    if (!isHighLight) {
        if (isMatch) {
            if (currentText.length > self.limitLength) {
                currentText = [currentText substringToIndex:self.limitLength];
            }
            self.historyText = self.text = currentText;
        }else{
            if (currentText.length == 0) {
                self.historyText = @"";
            }
            NSString *historyText = self.historyText;
            if (!historyText.length) {
                self.text = @"";
            } else {
                self.text = self.historyText;
                if (locationRange.location > 1) {
                    locationRange.location -= 1;
                }
            }
        }
    }
    
    
    if (locationRange.location > self.text.length) {
        locationRange.location = self.text.length;
    }
    [self setSelectedRange:locationRange];
}
- (void)selectAllText
{
    UITextRange *range = [self textRangeFromPosition:self.beginningOfDocument toPosition:self.endOfDocument];
    [self setSelectedTextRange:range];
}

- (NSRange) selectedRange
{
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextRange* selectedRange = self.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;
    
    const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

- (void)setSelectedRange:(NSRange)range
{
    UITextPosition *begin = [self positionFromPosition:self.beginningOfDocument offset:range.location];
    UITextPosition *end = [self positionFromPosition:self.beginningOfDocument offset:range.location + range.length];
    UITextRange *selectRange = [self textRangeFromPosition:begin toPosition:end];
    [self setSelectedTextRange:selectRange];
}


@end
